﻿<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/css/main.css">
    <link rel="stylesheet" href="/js/Grid/css/grid.css">
    <script src="/js/jquery-3.3.1.min.js"></script>
    <script src="/js/main.js"></script>
    <script src="/js/Grid/js/grid.js"></script>
    <script>
        ensureInFrame("/mysql_main.html");
    </script>
    <style>
        #tables {
            width: 80%;
            margin: 0 auto;
            table-layout: fixed;
            border-collapse: collapse;
        }

        #tables tr {
            line-height: 35px;
            height: 35px;
            text-align: center;
        }

        #tables td,
        #tables th {
            border: 1px solid #ddd;
        }

        #grid td span[data-name='desc']:hover {
            border: 1px solid #bfbdbd;
            padding: 3px;
        }
    </style>
    <style>
        .content {
            position: absolute;
            left: 660px;
            height: 100%;
            right: 0;
            overflow: hidden;
            z-index: 2;
            top: 0;
            background-color: rgba(255, 255, 255, 0.9);
            display: none;
        }

        .content iframe {
            width: 100%;
            height: 100%;
            border: none;
            overflow: hidden;
            position: absolute;
            top: 0;
            left: 0;
        }

        .border {
            width: 5px;
            top: 35px;
            bottom: 0;
            left: 660px;
            background-color: #999;
            cursor: col-resize;
            position: absolute;
            z-index: 99;
            display: none;
        }

        .content>.close {
            position: absolute;
            top: 0;
            left: 0;
            width: 35px;
            height: 35px;
            background-color: #999;
            color: #fff;
            z-index: 9;
        }

        .content>.close::after {
            display: block;
            content: "X";
            line-height: 35px;
            text-align: center;
        }

        .content>.close:hover {
            background-color: #333;
        }

        .split-shadow {
            position: absolute;
            z-index: 9;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
        }

        .not-select {
            user-select: none;
            -moz-user-select: none;
            -webkit-user-select: none;
        }
    </style>
    <!-- inner style -->
    <style>
        .inner-menu {
            position: absolute;
            left: 0;
            top: 50px;
            bottom: 0;
            width: 80px;
            border-right: 1px solid #ddd;
        }

        .inner-menu li {
            height: 60px;
            line-height: 60px;
            text-align: center;
            border: 1px solid #ddd;
            border-bottom: 0;
            cursor: pointer;
        }

        .inner-menu li.active {
            background-color: mediumseagreen;
            color: #fff;
        }

        .inner-menu li:last-child {
            border-bottom: 1px solid #ddd;
        }

        .inner-menu li:hover {
            color: #fff;
            background-color: mediumseagreen;
        }


        .inner-content {
            position: absolute;
            left: 85px;
            height: 100%;
            right: 0;
            overflow: hidden;
            z-index: 2;
            top: 50px;
        }

        .inner-content iframe {
            width: 100%;
            height: 100%;
            border: none;
            overflow: hidden;
            position: absolute;
            top: 0;
            left: 0;
            display: none;
        }

        .inner-title {
            padding-left: 80px;
            line-height: 50px;
        }

        .inner-title p {
            float: left;
            margin-right: 10px;
            font-size: 30px;
            color: red;
        }
    </style>
    <style>
        #header {
            height: 40px;
        }

        #schemaname {
            color: green;
        }

        #tablename {
            color: blue;
        }

        #filterSql {
            margin-left: 10px;
            position: relative;
            top: -5px;
            height: 40px;
            width: 400px;
            line-height: 40px;
            font-size: 18px;
        }
    </style>
</head>

<body>
    <div id="header">
        <p>
            <span>
                <input type="text" class="input" name="table" id="table" autocomplete="off" placeholder="请输入表名">
            </span>
            <span>
                <input type="text" class="input" name="desc" id="desc" autocomplete="off" placeholder="请输入表说明">
            </span>
            <span class="btn" onclick="refreshTables()">重新拉取列表</span>
            <span class="btn" onclick="exportCreateSql()">批量导出表结构</span>
            <span class="btn" onclick="exportCreateSqlAndInsertSql()">批量导出表结构和数据</span>
            <span style="padding-left: 15px;">已显示<font color="red" id="tableCountDisplay">...</font>条记录</span>
        </p>
    </div>
    <div id="grid"></div>
    <div class="border not-select"></div>
    <div class="content">
        <div class="close"></div>
        <div class="inner-menu not-select">
            <ul>
                <li class="active" data-target="db_table_data">数据</li>
                <li data-target="db_table_struct">结构</li>
                <li data-target="db_table_sql">Sql</li>
                <li data-target="db_table_constraint">约束</li>
                <li data-target="db_table_index">索引</li>
                <li data-target="db_table_trigger">触发器</li>
                <li data-target="db_table_export">导出</li>
                <li data-target="db_table_code">代码生成</li>
            </ul>
        </div>
        <div class="inner-title">
            <p>
                表：<font id="tablename"></font>
                <input type="text" id="filterSql" style="margin-left: 10px;" class="input" placeholder="请输入过滤条件" />
            </p>
        </div>
        <div class="inner-content">
            <iframe style="display: block;" id="db_table_data" src="table/db_table_data.html" frameborder="0"></iframe>
            <iframe id="db_table_struct" src="table/db_table_struct.html" frameborder="0"></iframe>
            <iframe id="db_table_sql" src="table/db_table_sql.html" frameborder="0"></iframe>
            <iframe id="db_table_constraint" src="table/db_table_constraint.html" frameborder="0"></iframe>
            <iframe id="db_table_index" src="table/db_table_index.html" frameborder="0"></iframe>
            <iframe id="db_table_trigger" src="table/db_table_trigger.html" frameborder="0"></iframe>
            <iframe id="db_table_export" src="table/db_table_export.html" frameborder="0"></iframe>
            <iframe id="db_table_code" src="table/db_table_code.html" frameborder="0"></iframe>
        </div>
    </div>
    <!-- split control -->
    <script>
        $(function () {
            $(".inner-content iframe").each(function (index, ele) {
                var url = $(ele).attr("src");
                var t = new Date().getTime();
                url += "?_t=" + t;
                $(ele).attr("src", url);
            });
            $(".content>.close").click(function () {
                $(".content").hide();
                $(".border").hide();
            });
            $(".border").mousedown(function (evt) {
                var x, y, box = $(".content"), border = $(".border");
                var shadowDom = $(`<div class="split-shadow"></div>`).appendTo(document.body);
                box.addClass("not-select");

                function move(evt) {
                    var x = evt.pageX;
                    box.css("left", x + "px");
                    border.css("left", x + "px");
                }
                function offEvent() {
                    $(document.body).off("mousemove", move);
                    if (shadowDom) shadowDom.remove();
                    box.remove("not-select");
                }
                $(document.body).mousemove(move).mouseup(offEvent);
            });
            $("#filterSql").keydown(evt => {
                if (evt.keyCode == 13) {
                    sendReload();
                }
            });
        })
    </script>
    <!-- tables -->
    <script>
        var __timeout;
        $(function () {
            refreshTables();
            // $("#schema,#table,#desc").on("input", evt => {
            //     if (__timeout) clearTimeout(__timeout);
            //     __timeout = setTimeout(filterTables, 600);
            // });
            $("#table,#desc").on("keydown", evt => {
                if (evt.keyCode == 13) {
                    filterTables();
                }
            });
        })
        var table;
        var height = document.body.clientHeight - 10 - 35;
        var grid = new Grid("grid", {
            isFixHead: true,
            sizeColumn: true,
            isEdit: true,
            height: height,
            isPage: false,
            colWidths: [
                30, 30, 150, 150, 40, 80, 50, 50, 50, 50, 100, 100
            ],
            headArr: [
                [
                    { rowspan: 2, type: "chk" },
                    { text: "序号", rowspan: 2 },
                    { text: "名称", order: { type: "none", name: "name", rank: 2 }, rowspan: 2 },
                    { text: "说明", rowspan: 2 },
                    { text: "自增量", rowspan: 2 },
                    { text: "排序规则", rowspan: 2 },
                    { text: "记录数", order: { type: "none", name: "rowCount", rank: 3 }, rowspan: 2 },
                    { text: "占用空间", colspan: 4 },
                    { text: "创建时间", order: { type: "none", name: "createTime", rank: 5 }, rowspan: 2, }
                ],
                [
                    { text: "总空间", order: { type: "none", name: "allSize", rank: 4 } },
                    { text: "数据占用" },
                    { text: "索引占用" },
                    { text: "未分配" }
                ]
            ],
            columnArr: [
                { type: "chk", selectRow: true },
                { type: "index" },
                { type: "lab", name: "name" },
                {
                    type: "lab", name: "desc", cutLen: 20, title: "desc", dblClick: function (text, data, tr, div) {
                        var desc = window.prompt("请输入表说明:", data.desc ?? "");
                        if (desc == null) {
                            //取消编辑
                            return;
                        }
                        var name = data.name;
                        showLoading();
                        $.post("/api/mysqlmanage/UpdateTableDescription", { name, desc }).done(res => {
                            if (res.success) {
                                div.html(desc);
                                data.desc = desc;
                            } else {
                                alert(res.message);
                            }
                        }).always(hideLoading);
                    }
                },
                { type: "lab", name: "identity" },
                { type: "lab", name: "collection" },
                { type: "lab", name: "rowCount" },
                { type: "lab", name: "allSize" },
                { type: "lab", name: "dataSize" },
                { type: "lab", name: "indexSize" },
                { type: "lab", name: "unUsedSize" },
                { type: "lab", name: "createTime" }
            ],
            onQuery: function (pageIndex, pageSize, orders) {
                displayTables();
            },
            onRowDblClick: function (row, tr, index) {
                if (table != row.name) {
                    $("#filterSql").val("");
                }
                table = row.name;
                grid.selectRow(tr);
                loadTableDetail();
            },
            onRowClick: function (row, tr, index) {
                if (!$(".content").is(":hidden")) {
                    if (table != row.name) {
                        $("#filterSql").val("");
                    }
                    table = row.name;
                    grid.selectRow(tr);
                    loadTableDetail();
                }
            }
        });

        //从后台拿到的数据
        var all_tables;
        function refreshTables() {
            showLoading();
            $.get("/api/mysqlmanage/GetAllTables").done(res => {
                if (res.success) {
                    all_tables = dealDataSize(res.data);
                    displayTables();
                }
            }).always(hideLoading);
        }
        var loadDom;
        var log = 1;
        function displayTables() {
            showLoading();
            setTimeout(() => {
                tables = $.extend(true, [], all_tables);
                grid.init({ data: grid.order(tables) });
                hideLoading();
                filterTables();
            }, 0);
            return;
        }
        //排序处理后的数据
        var tables;
        function _filterTables() {
            var table = $("#table").val().trim();
            var desc = $("#desc").val().trim();

            var hideIndex = [];
            if (table || desc) {
                //存在过滤条件
                for (var i = tables.length - 1; i >= 0; i--) {
                    var item = tables[i];
                    //按表名过滤
                    if (!item.name.toUpperCase().includes(table.toUpperCase())) {
                        //不显示
                        hideIndex.push(i);
                        //去掉标红
                        var span = $("#grid .grid-body tr[rowindex='" + i + "'] td span[data-name='name']");
                        if (span.html().includes("font")) {
                            span.html(item.name);
                        }
                        continue;
                    } else {
                        //显示
                        if (table.length > 0) {
                            //标红
                            var upName = item.name.toUpperCase();
                            var sName = table.toUpperCase();
                            var start = upName.indexOf(sName);
                            var len = sName.length;
                            var repName = item.name.substr(start, len);
                            var span = $("#grid .grid-body tr[rowindex='" + i + "'] td span[data-name='name']");
                            var displayName = item.name.replace(repName, "<font color='red'>" + repName + "</font>");
                            span.html(displayName);
                        } else {
                            //去掉标红
                            var span = $("#grid .grid-body tr[rowindex='" + i + "'] td span[data-name='name']");
                            if (span.html().includes("font")) {
                                span.html(item.name);
                            }
                        }
                    }
                    //按表说明过滤
                    if (!(item.desc ?? "")?.toUpperCase().includes(desc.toUpperCase())) {
                        hideIndex.push(i);
                        //去掉标红
                        var span = $("#grid .grid-body tr[rowindex='" + i + "'] td span[data-name='desc']");
                        if (span.html().includes("font")) {
                            span.html(item.name);
                        }
                        continue;
                    } else {
                        //显示
                        if (desc.length > 0) {
                            //标红
                            var upDesc = item.desc.toUpperCase();
                            var sDesc = desc.toUpperCase();
                            var start = upDesc.indexOf(sDesc);
                            var len = sDesc.length;
                            var repDesc = item.desc.substr(start, len);
                            var span = $("#grid .grid-body tr[rowindex='" + i + "'] td span[data-name='desc']");
                            var displayName = item.desc.replace(repDesc, "<font color='red'>" + repDesc + "</font>");
                            span.html(displayName);
                        } else {
                            //去掉标红
                            var span = $("#grid .grid-body tr[rowindex='" + i + "'] td span[data-name='desc']");
                            if (span.html().includes("font")) {
                                span.html(item.desc);
                            }
                        }
                    }
                }
                if (hideIndex.length > 0) {
                    var selectors = hideIndex.map(i => "#grid .grid-body tr[rowindex='" + i + "']");
                    var str = selectors.join(",");
                    $("#grid .grid-body tr[rowindex]").show();
                    $(str).hide();
                } else {
                    $("#grid .grid-body tr[rowindex]").show();
                }
            } else {
                //不存在过滤条件
                //标红的全部去掉
                var spans = $("#grid .grid-body tr[rowindex] td span[data-name='name'],#grid .grid-body tr[rowindex] td span[data-name='desc']");
                var fonts = spans.find("font");
                spans = fonts.parent("span");
                spans.each((index, ele) => {
                    var span = spans.eq(index);
                    span.html(span.text());
                });
                //全部显示
                $("#grid .grid-body tr[rowindex]").show();
            }
            //显示的数量
            $("#tableCountDisplay").html(tables.length - hideIndex.length);
        }
        function filterTables() {
            showLoading();
            setTimeout(() => {
                _filterTables();
                hideLoading();
            }, 0);
        }
        function dealDataSize(data) {

            return data;
        }
        function loadTableDetail() {
            if ($(".content").is(":hidden")) {
                $(".content").show();
                $(".border").show();
            }
            sendReload();
        }
        function getSelectedRows() {
            var rows = grid.getSelectedRows();
            for (var i = rows.trs.length - 1; i >= 0; i--) {
                var row = rows.trs.eq(i);
                if (row.is(":hidden")) {
                    //移除这一行
                    var rowindex = row.attr("rowindex");
                    rows.trs = rows.trs.filter("[rowindex!='" + rowindex + "']");
                    rows.data.splice(i, 1);
                }
            }
            return rows;
        }
        function exportCreateSql() {
            var rows = getSelectedRows();
            if (rows.data.length == 0) {
                alert("请先选择要导出的表!");
                return;
            }
            var tables = [];
            for (var i = 0; i < rows.data.length; i++) {
                tables.push({
                    name: rows.data[i].name,
                })
            }
            showLoading();
            $.ajax({
                url: "/api/mysqlmanage/GetCreateTableSqlBatch",
                type: "post",
                async: true,
                data: JSON.stringify(tables),
                contentType: "application/json"
            }).done(res => {
                if (res.success) {
                    res.data = res.data.replace("\\", "/");
                    var a = $(`<a id="jiko" href='/api/mysqlmanage/DownLoadExportSql?filename=${res.data}' download='${res.data}'>下载</a>`).hide().appendTo(document.body);
                    a[0].click();
                    setTimeout(() => a.removeClass(), 1000);
                } else {
                    alert(res.message);
                }
            }).always(hideLoading);
        }
        function exportCreateSqlAndInsertSql() {
            var rows = getSelectedRows();
            if (rows.data.length == 0) {
                alert("请先选择要导出的表!");
                return;
            }
            var tables = [];
            for (var i = 0; i < rows.data.length; i++) {
                tables.push({
                    name: rows.data[i].name
                })
            }
            showLoading();
            $.ajax({
                url: "/api/mysqlmanage/GetCreateInsertTableSqlBatch",
                type: "post",
                async: true,
                data: JSON.stringify(tables),
                contentType: "application/json"
            }).done(res => {
                if (res.success) {
                    res.data = res.data.replace("\\", "/");
                    var a = $(`<a id="jiko" href='/api/mysqlmanage/DownLoadExportSql?filename=${res.data}' download='${res.data}'>下载</a>`).hide().appendTo(document.body);
                    a[0].click();
                    setTimeout(() => a.removeClass(), 1000);
                } else {
                    alert(res.message);
                }
            }).always(hideLoading);
        }
    </script>
    <!-- table inners -->
    <script>
        var currentPage;
        $(function () {
            currentPage = $(".content iframe");
            $(".inner-menu li").click(evt => {
                var li = $(evt.target);
                var targetId = li.attr("data-target");
                li.parent().children().removeClass("active");
                li.addClass("active");
                currentPage = $("#" + targetId);
                $(".inner-content iframe").hide();
                currentPage.show();
                if(["db_table_data","db_table_export"].includes(targetId)){
                    $("#filterSql").show();
                }else{
                    $("#filterSql").hide();
                }
                sendReload();
            });
            //设置数据库名称
            var db = getCurrentDb();
        });
        function sendReload() {
            var currentInnerWindow = currentPage[0].contentWindow;
            var filter = $("#filterSql").val();
            currentInnerWindow.postMessage({ table, filter });
            $("#tablename").html(table);
        }

    </script>
</body>

</html>